package com.karst.essentials.chapter07.galaxyExample
{
	import flash.display.BitmapData;
	
	import org.papervision3d.core.proto.GeometryObject3D;
	import org.papervision3d.events.FileLoadEvent;
	import org.papervision3d.lights.PointLight3D;
	import org.papervision3d.materials.BitmapFileMaterial;
	import org.papervision3d.materials.ColorMaterial;
	import org.papervision3d.materials.shaders.PhongShader;
	import org.papervision3d.materials.shaders.ShadedMaterial;
	import org.papervision3d.objects.DisplayObject3D;
	import org.papervision3d.objects.primitives.Plane;
	import org.papervision3d.objects.primitives.Sphere;
	
	internal class Galaxy extends DisplayObject3D
	{
		public function Galaxy()
		{
			super();
			createView() ;
		}

		private var light : PointLight3D = null ;
		private var bmpMaterial : BitmapFileMaterial = null ;
		private var shadedMaterial : ShadedMaterial = null ;
		private var earthSphere : Sphere = null ;
		private function createView() : void
		{
			if( light == null )
			{
				light = new PointLight3D() ;
				light.x = 5000 ;
				light.y = 6000 ;
				light.z = -6000 ;
			}
			if( bmpMaterial == null )
			{
				bmpMaterial = new BitmapFileMaterial( "earth.jpg" ) ;
				bmpMaterial.addEventListener( FileLoadEvent.LOAD_COMPLETE, loadedBmpHandler ) ;
			}
			
			for( var i : int = 0; i < 150; i++ )
			{
				var plane : Plane = new Plane( 
					new ColorMaterial( Math.random() * 0xFFFFFF ), 50, 50, 1, 1 ) ;
				plane.material.doubleSided = true ;
				addChild( plane ) ;
				plane.x = Math.random() * 20000 - 10000 ;
				plane.y = Math.random() * 1500 - 750 ;
				plane.z = Math.random() * 20000 - 10000 ;
				plane.localRotationY = Math.random() * 180 - 90 ;
			}
		}
		
		private function loadedBmpHandler( event : FileLoadEvent ) : void
		{
			if( shadedMaterial == null )
			{
				var bumpBmpData : BitmapData = new BitmapData( bmpMaterial.bitmap.width, bmpMaterial.bitmap.height ) ;
				bumpBmpData.perlinNoise( 10, 10, 1, Math.random()*100, true, false, 1, true ) ;
				
				shadedMaterial = new ShadedMaterial( bmpMaterial, 
					new PhongShader( light, 0xFFFFFF, 0x00000022, 0, bumpBmpData ) ) ;
			}
			if( earthSphere == null )
			{
				earthSphere = new Sphere( shadedMaterial, 200, 24, 26 ) ;
			}
			addChild( earthSphere ) ;
		}
		
		public function update() : void
		{
			if( earthSphere )
			{
				earthSphere.localRotationY += .2 ;
			}
		}
	}
}